package concurrency.chapter12;

import java.util.Arrays;

/**
 * @author 夏焰波
 * @date 2020-06-09 1:33
 */
public class ThreadGroupCreate {
    public static void main(String[] args) {
        //use the name

        ThreadGroup tg1 = new ThreadGroup("TG1");
        Thread t1 = new Thread(tg1, "t1") {
            @Override
            public void run() {
                while (true) {
                    try {
                        //System.out.println(getThreadGroup().getName());//TG1
                        //System.out.println(getThreadGroup().getParent().getName());//main
                        //可以访问父线程的信息
                        //System.out.println(getThreadGroup().getParent().activeCount());//main
                        //sleep不会放弃cpu执行权进入block状态
                        Thread.sleep(2_000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        };
        t1.start();
        //ThreadGroup tg2 = new ThreadGroup(tg1, "TG2");
        //System.out.println(tg2.getName());//TG2
        //System.out.println(tg2.getParent().getName());//TG1

        ThreadGroup tg3 = new ThreadGroup("TG3");
        Thread t3=new Thread(tg3,"T3"){
            @Override
            public void run() {
                System.out.println(tg3.getName());
                Thread[] threads=new Thread[tg1.activeCount()];
                //enumerate方法用来将ThreadGroup线程组中的active线程全部复制到Thread类型的数组中，并且返回数组中元素个数，即线程组中active线程数量。
                int enumerate = tg1.enumerate(threads);
                System.out.println(enumerate);
                Arrays.asList(threads).forEach(System.out::println);
            }
        };
        t3.start();

        //use the parent and group

        //main线程是由jvm创建
        //System.out.println(Thread.currentThread().getName());//main
        //System.out.println(Thread.currentThread().getThreadGroup().getName());//main
    }
}
